<script setup>
import _ from 'lodash'
import common from './common';
// import formService from './form-service.vue';
import formModule from './form-module.vue';
import {onMounted, reactive, toRefs} from "vue";
import {api} from "@jzl/api";
import {$utils, $jui} from '@jzl/utils'
import {DFT_ICONS} from "@jzl/icons";

const emit = defineEmits(['select'])
const props = defineProps({
  appId: Number
})

const {
  apps,
  loading,
  selectData,
  currentData,
  currentApp,
  actionType,
  expandedKeys,
  treeSetting,
  formSvcWinName,
  formSvcWinShow,
  formModuleWinName,
  formModuleWinShow,
} = toRefs(reactive({
  apps: [],
  loading: false,
  selectData: {},
  currentData: {},
  currentApp: {},

  actionType: 'view',     // createGroup | createMb | edit | view
  expandedKeys: [],
  // checkedKeys: [],
  treeSetting: {
    children: 'subs',
    label: 'name',
    'icon-class': 'hello-icon'
  },

  formSvcWinName: '',
  formSvcWinShow: false,
  formModuleWinName: '',
  formModuleWinShow: false,
}))

onMounted(() => {
  init()
})

const isActive = (data) => {
  return selectData.value && data && selectData.value.svc_module_id === data.svc_module_id;
}

const init = async () => {
  await loadRoot();

  let ids = _.map(apps.value, 'id');
  expandedKeys.value = ids;
}

const getModules = async () => {
  let modules = await api.services.moduleListAll();
  return modules;
}

const refreshCurrentNode = async (key) => {
  await init();

  let id = _.get(currentData.value, 'tid');

  if (key) {
    id = key;
  }

  let paths = $utils.getTreePath(tid, apps.value, 'tid', 'subs', true);
  let info = _.find(paths, {tid: tid});

  expandedKeys.value = _.map(paths, 'tid');
  handleClick(info);
}

const loadRoot = async () => {

  loading.value = true;
  let iApps = await loadApps();
  let modules = await getModules();

  _.each(iApps, app => {
    app.subs = _.filter(modules, {app_id: app.id});
  });

  apps.value = iApps;
  // this.modules = modules;
  loading.value = false;
}

const loadApps = async () => {
  let ret = await api.admin.getMyApps();
  let myApps = _.get(ret, 'apps', []);
  // let ret = await api.admin.getAdminMenuTree(null, 1);
  // let groups = _.get(ret, 'groups', []);
  let apps = _.map(myApps, app => {
    return {
      nodeType: 'app',
      name: `${_.get(app, 'group_name')}-微模块`,
      id: _.get(app, 'group_id'),
      tid: _.get(app, 'group_id'),
      isApp: true
    }
  });
  if (props.appId) {
    apps = _.filter(apps, ap => {
      return ap && (ap.id === props.appId || ap.id < 0)
    });
  }

  return apps;
}

const handleClick = async (data, node, ele) => {
  selectData.value = data;
  if (!data) return;

  emit("select", data);
}

const handleShowCreateModule = (app) => {
  actionType.value = 'create';
  currentApp.value = app;

  if (!currentApp.value) return;

  let name = _.get(currentApp.value, 'name');

  formModuleWinName.value = `【${name}】下注册模块`;
  formModuleWinShow.value = true;
}

const handleShowEdit = (data) => {

  currentData.value = data;

  let name = _.get(currentData.value, 'svc_module_name');

  actionType.value = 'edit';
  formModuleWinShow.value = true;
  formModuleWinName.value = `修改模块【${name}】`;
}

const handleShowDelete = async (dt) => {

  currentData.value = dt;

  if (!dt) return;

  let name = _.get(dt, 'svc_module_name');
  let typeName = '模块';

  let msg = `确定删除${typeName}【${name}】?`;
  $jui.confirm(msg, '删除确认').then(async () => {
    // let id = null;
    let ret = await api.services.moduleRemove(dt.svc_module_id);

    if (!ret) return;

    currentData.value = {};
    init();
  }).catch(e => {

  });
}

const handleTreeCommand = (cmd, data) => {
  currentData.value = data;

  if (cmd === 'svc') {
    // handleShowCreateSvc(data);
  } else if (cmd === 'module') {
    handleShowCreateModule();
  } else if (cmd === 'edit') {
    handleShowEdit(data);
  } else if (cmd === 'remove') {
    handleShowDelete(data);
  }
}

const handleFormClose = (isUpdate) => {
  formSvcWinShow.value = false;
  formModuleWinShow.value = false;

  if (isUpdate) {
    refreshCurrentNode();
  }
}
</script>
<template>
  <el-scrollbar
    class="apps-cate"
    v-loading="loading"
  >
    <div v-for="app in apps">
      <div class="app-form-group-label">{{ app.name }}
        <JIcon
          :icon="DFT_ICONS.add"
          class="svc-create"
          v-tippy="{ arrow: true }"
          content="注册微模块"
          @click="handleShowCreateModule(app)"
        />
      </div>
      <span
        v-for="data in app.subs"
        class="menu-custom-tree-node app-cate-item"
        :class="{ 'active': isActive(data) }"
        @click="handleClick(data)">
        <span
          class="menu-custom-icon"
          :class="{
            'menu-icon-module': data.svc_module_type === 1,
            'menu-icon-api': data.svc_module_type === 2
          }">
          <JIcon :icon="data.svc_module_type === 1 ? DFT_ICONS.module: DFT_ICONS.api" />
        </span>
        <span>{{ data.svc_module_name }}
          <span style="color: #CCC;" v-if="data.svc_module_code">（{{
              data.svc_module_code
            }}）</span>
        </span>
        <!--<i class="el-icon-edit btn-more" @click="handleShowEdit(data)" v-tippy="{ arrow: true }" content="修改" style="right: 12px;"></i>-->
        <div @click.stop>
            <el-dropdown
              trigger="click"
              placement="bottom-start"
              size="small"
              style="position:absolute;right: 0px;"
              @command="handleTreeCommand($event, data)">
              <JIcon
                :icon="DFT_ICONS.more"
                class="btn-more"
                v-tippy="{ arrow: true }"
                content="更多操作"
                style="right: 12px;"/>
              <template #dropdown>
                <el-dropdown-menu>
                    <!--<template v-if="isGlobal(data) || isApp(data)">
                        <el-dropdown-item command="svc"><i class="el-icon-plus"></i>微服务</el-dropdown-item>
                    </template>
                    <template v-if="isService(data)">
                        <el-dropdown-item command="module"><i class="el-icon-plus"></i>模块</el-dropdown-item>
                    </template>
                    <template v-if="isService(data) || isModule(data)">-->
                    <el-dropdown-item command="edit"><i class="el-icon-edit"></i>修改</el-dropdown-item>
                    <el-dropdown-item command="remove"><i class="el-icon-delete"></i>删除</el-dropdown-item>
                  <!--</template>-->
                </el-dropdown-menu>
                </template>
            </el-dropdown>
        </div>
      </span>

      <!--<el-tree v-if="app.subs && app.subs.length" ref="mbtree"
               class="menu-custom-tree menu-tree-svcs"
               :data="app.subs"
               node-key="tid"
               :highlight-current="true"
               :default-expanded-keys="expandedKeys"
               :props="treeSetting"
               @click.native.stop="empty"
               @node-click="x">
          <span class="menu-custom-tree-node"
                :class="{ 'menu-icon-node': isRootMenu(data), 'menu-icon-active': isActive(data) }"
                slot-scope="{ node, data }">
              <span class="menu-custom-icon"
                    :class="{
                      'menu-root-icon': isService(data),
                      'menu-icon-module': isModuleForm(data),
                      'menu-icon-api': isModuleApi(data)}">
                  <template v-if="isRootMenu(data)">
                      <i class="fa menu-icon-white" :class="{
                          'fa-globe-asia': isPlatform(data),
                          'fa-google': isGlobal(data),
                          'fa-app-store': isApp(data),
                          'fa-docker': isService(data),
                          'fa-medium-m': isModuleForm(data),
                          'fa-telegram-plane': isModuleApi(data)
                      }"></i>
                      <i class="fa menu-icon-color" :class="{
                          'fa-globe-asia': isPlatform(data),
                          'fa-google': isGlobal(data),
                          'fa-app-store': isApp(data),
                          'fa-docker': isService(data),
                          'fa-medium-m': isModuleForm(data),
                          'fa-telegram-plane': isModuleApi(data)
                      }"></i>
                  </template>

                  <i v-else class="fa" :class="{
                      'fa-globe-asia': isPlatform(data),
                      'fa-google': isGlobal(data),
                      'fa-app-store': isApp(data),
                      'fa-docker': isService(data),
                      'fa-medium-m': isModuleForm(data),
                      'fa-telegram-plane': isModuleApi(data)
                  }"></i>
              </span>
              <span>{{data.name}}<span style="color: #CCC;" v-if="data.code">（{{data.code}}）</span></span>

              <div @click.stop="empty" v-if="canEdit(data)">
                  <el-dropdown trigger="click" placement="bottom-start" size="small" style="position:absolute;right: 0px;"
                               @command="handleTreeCommand($event, data)">
                      <i class="el-icon-more btn-more" v-tippy="{ arrow: true }" content="更多操作"></i>
                      <el-dropdown-menu slot="dropdown">
                          <template v-if="isGlobal(data) || isApp(data)">
                              <el-dropdown-item command="svc"><i class="el-icon-plus"></i>微服务</el-dropdown-item>
                          </template>
                          <template v-if="isService(data)">
                              <el-dropdown-item command="module"><i class="el-icon-plus"></i>模块</el-dropdown-item>
                          </template>
                          <template v-if="isService(data) || isModule(data)">
                              <el-dropdown-item command="edit"><i class="el-icon-edit"></i>修改</el-dropdown-item>
                              <el-dropdown-item command="remove"><i class="el-icon-delete"></i>删除</el-dropdown-item>
                          </template>
                      </el-dropdown-menu>
                  </el-dropdown>
              </div>
          </span>
      </el-tree>-->
    </div>

    <!--<el-dialog :title="formSvcWinName" :visible.sync="formSvcWinShow" :close-on-click-modal="false" :append-to-body="true">
        <form-service v-if="formSvcWinShow" :current-data="currentData" @close="handleFormClose"></form-service>
    </el-dialog>-->

    <el-dialog
      :title="formModuleWinName"
      v-model="formModuleWinShow"
      :close-on-click-modal="false"
      :append-to-body="true">
      <form-module
        v-if="formModuleWinShow"
        :current-data="currentData"
        :app="currentApp"
        :action-type="actionType"
        @close="handleFormClose"></form-module>
    </el-dialog>
  </el-scrollbar>
</template>

<style lang="scss" scoped>
/*.apps-cate {
  border-radius: 0px;
  border: none;
  box-shadow: none;
  margin-right: 0px;
}*/
.mb-info {
  display: flex;
  flex-flow: column;
  padding: 10px;

  .m-table-container {
    flex: 1;
    height: 100%;
  }
}

.app-form-group-label {
  position: relative;
}

.svc-create {
  position: absolute;
  right: 5px;
  font-size: 12px;
  width: 18px;
  height: 18px;
  border-radius: 5px;
  text-align: center;
  line-height: 18px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;

  &:hover {
    color: rgb(153, 153, 153);
    background: #F5F5F5;
  }
}
.menu-tree-svcs {
  .el-tree-node {
    position: relative;
  }

  .el-tree-node__content {
    position: relative;
  }
}

.menu-custom-tree-node.menu-icon-active {
  &:before {
    content: ' ';
    position: absolute;
    left: 1px;
    top: 0px;
    bottom: 0px;
    right: 0px;
    border: 1px solid #4ea3fb;
  }
}
</style>
